# -*- coding: utf-8 -*-
import pandas as pd
import os
import xlwt
import numpy as np
import scipy
import skin_resistor.line as lineParser
from skin_resistor.info import skinInfoType
import skin_resistor as skinRes
import skin_resistor.excel as skinExcel 
from PyQt5 import QtCore, QtGui, QtWidgets, QtSerialPort
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtSerialPort import *

# def createCoreActiveChart(worksheet, workbook, sheet, actPos, xHead, xPos, xPosInc):
#     chartId = 1
#     xpos = xPosInit
#     xHead = xHeadInit

#     for now in chartBaseInfo:
#         chartName = '区间图 ' + str(chartId) + '.'
#         chartName += str(now[0])
#         chartName += '_' + str(now[4])

#         if now[5] != 0:
#             chartName += '_' + str(now[5])

#         if now[6] != 0:
#             chartName += '_' + str(now[6])

#         if now[7] != 0:
#             chartName += '_体感' + str(now[7])

#         chartPos = xHead + str(xpos)

#         createSingleLineChart(worksheet, workbook, sheet, chartName, chartPos, 'A', 'B', now[1], now[2], True, 'C');

#         print(now, chartName, chartPos)
#         chartId += 1
#         xpos += xPosInc
'''
# 导入文件
'''
def importSkinDataFromCsvFile(filename):
    data = []
    file = QFile(filename)

    if file.open(QFile.ReadOnly | QFile.Text) == False:
        return data

    while file.atEnd() == False:
        line = file.readLine()
        lineStr = str(line, encoding='utf-8')
        # print(lineStr)
        data.append(lineStr)

    file.close()

    return data

def importSkinResistorData(parent):
    data = []
    formatList = 'csv Files (*.csv);;text Files (*.txt);;xlsx Files (*.xlsx);;mat Files (*.mat)'
    filename, ok = QFileDialog.getOpenFileName(parent, '文件保存', './', formatList)

    if ok == '':
        return

    fmt = os.path.splitext(filename)[1]
    fmt = fmt.lower()

    # 导出txt csv文件
    if fmt == '.txt' or fmt == '.csv':
        data = importSkinDataFromCsvFile(filename)
        if len(data) == 0:
            QMessageBox.critical(parent, "错误", filename + "文件保存失败!")
    else:
        QMessageBox.critical(parent, "status", filename + "文件导入失败，不支持的文件格式!")

    return data

'''
# 导出文件
'''
def exportSkinDataToExcelFile(path, data):
    if len(data) == 0:
        return 0

    dataLen = len(data)
    lineLen = len(data[0])
    # print(path, str(dataLen) + 'x' + str(lineLen))

    excel_file = path
    sheet = 'sheet1'

    f = xlwt.Workbook()
    sheet1 = f.add_sheet(sheet, cell_overwrite_ok=True)  # 创建sheet
    # 写入数据到excel中
    for x in range(dataLen):
        lineData = data[x]
        for y in range(lineLen):
            # print(x, lineData[y])
            sheet1.write(x, y, lineData[y])

    f.save(excel_file)  # 保存文件

    df = pd.read_excel(path, sheet_name=sheet, header = None)
    writer = pd.ExcelWriter(excel_file, engine='xlsxwriter')
    df.to_excel(writer, sheet_name=sheet, startrow=0, startcol=0, header=False, index=False)
    
    workbook = writer.book
    worksheet = writer.sheets[sheet]

    # 生成图表
    # 生成机芯动作曲线图
    # createPartChart(worksheet, workbook, sheet, 'X', 20, 45)

    writer.save()

    return 1

def exportSkinDataToCsvFile(path, data): 
    if len(data) == 0:
        return 0

    dataLen = len(data)
    lineLen = len(data[0])
    # print(path, str(dataLen) + 'x' + str(lineLen))

    file = QFile(path)

    if file.open(QFile.ReadWrite | QFile.Truncate) == False:
        return 0

    outText = QTextStream(file)

    for x in range(dataLen):
        lineData = data[x]
        writeString = ''
        for y in range(lineLen):
            writeString += str(lineData[y])
            
            if y != (lineLen-1):
                writeString += ','

        writeString += '\n'
        outText << writeString

    file.close()

    return 1

def exportSkinDataToMatFile(path, data): 
    if len(data) == 0:
        return 0

    dataLen = len(data)
    lineLen = len(data[0])
    # print(path, str(dataLen) + 'x' + str(lineLen))

    # matData = np.mat(data)

    mdict = {}
    

    info = skinInfoType(data[0])
    
    arr = []
    
    for y in range(lineLen):
        writeData = []
        for x in range(dataLen):
            writeData.append(data[x][y])

        arr.append(writeData)
        mdict[info.enTitle[y]] = writeData

    # mdict = np.mat(data)
    # print(mdict)

    scipy.io.savemat(path,  mdict)

    return 1

def exportSkinDataToCHeadFile(path, data, curTimeStr):
    filePathInfo = os.path.splitext(path)
    temp = filePathInfo[0] + '.h'
    headBaseFileName = os.path.split(temp)[1]

    dirname,filename = os.path.split(path)
    headFilePath = dirname + r'/' + str('skin_data_%s.h'%(curTimeStr))

    # print(headFilePath)

    # 生成头文件
    headStr =  str('/*\n  %s Generated by SkinDataParserTool'%(headBaseFileName))
    headStr += '\n  Author: Accumulate Team'
    headStr += '\n  Ver: 1.0.0'
    headStr += str('\n  Compiled time: %s'%(getCurTime(4)))
    headStr += str('\n  Generated time:%s'%(getCurTime(4)))
    headStr += '\n*/\n\n'

    headStr += str('#ifndef __SKIN_TEMP_DATA_%s__\n'%(curTimeStr))
    headStr += str('#define __SKIN_TEMP_DATA_%s__\n\n'%(curTimeStr))

    headStr += '#include "skin_temp_data.h"\n\n'

    headStr += str('extern const struct SKIN_TEMP_DATA skinTempData_%s[%d];\n\n'%(curTimeStr, len(data)))

    headStr += '#endif\n\n'
    headStr += '/**********************************END OF FILE*********************************/\n';

    file = QFile(headFilePath)
    file.open(QFile.ReadWrite | QFile.Truncate)
    file.close()
    file.open(QFile.ReadWrite)

    outText = QTextStream(file)
    outText << headStr
    file.close()

def exportSkinDataToCSourceFile(path, data, index, curTimeStr):
    if len(data) == 0:
        return 0

    filePathInfo = os.path.splitext(path)[0]
    srcFilePath = filePathInfo + '.c'
    # headFilePath = filePathInfo + '.h'
    srcBaseFileName = os.path.split(srcFilePath)[1]
    # headBaseFileName = os.path.split(headFilePath)[1]
    # print(srcFilePath, srcBaseFileName, headFilePath, headBaseFileName)
    dirname,filename = os.path.split(path)
    # headFilePath = dirname + r'/' + str('skin_data_%s.h'%(curTimeStr))
    srcFilePath = dirname + r'/' + str('skin_data_%s.c'%(curTimeStr))

    srcStr =  str('/*\n  src file:%s'%(srcBaseFileName))
    srcStr += str('\n  Soreness Index:neck:%d, shd:%d, back up:%d, back down:%d, waist:%d, hip:%d'
                  %(index[0], index[1], index[2], index[3], index[4], index[5]))

    srcStr += '\n  Author: Accumulate Team'
    srcStr += '\n  Ver: 1.0.3'
    srcStr += str('\n  Generated time: %s'%(getCurTime(4)))
    srcStr += str('\n  Generated by Skin Data Parser Tool')
    srcStr += '\n*/\n\n'

    srcStr += str('#include "skin_test_data.h"\n\n')
    srcStr += str("const char *SKIN_SCAN_DATA_INFO_CONNECT(%s) = \"%s-%s,"\
                  "Soreness Index:neck:%d, shd:%d, back up:%d, back down:%d, waist:%d, hip:%d\";\n\n"
                  %(curTimeStr, srcBaseFileName, curTimeStr, index[0], index[1], index[2], index[3], index[4], index[5]))

    srcStr += str('const struct SKIN_TEST_DATA SKIN_SCAN_DATA_CONNECT(%s)[%d] = \n{\n'%(curTimeStr, len(data)))
    for temp in data:
        info = skinInfoType(temp)

        srcStr += str("    {.value=%d, .srcValue=%d, .lod=%d, "\
                      ".skinCheckState=%d, .massagePart=%d, .massagePartState=%d, "\
                      ".massageState=%d, .coreWalkPercent=%d, .coreKneadPoint=%d, "\
                      ".coreKneadPart=%d, .coreKneadSpeed=%d, .coreD3Level=%d,},\n"
                      %(info.resistorValue, info.placeholder, info.lodState, info.skinCheckState,
                        info.massagePart, info.massagePartState, info.massageState, info.walkPercent,
                        info.kneadPoint, info.kneadPart, info.kneadSpeed, info.d3UpLevel))

    srcStr += str('};\n\n')
    srcStr += '/**********************************END OF FILE*********************************/\n';

    file = QFile(srcFilePath)
    file.open(QFile.ReadWrite | QFile.Truncate)
    file.close()
    file.open(QFile.ReadWrite)

    outText = QTextStream(file)
    outText << srcStr
    file.close()

    return 1

def exportSkinDataToLanguageCFile(path, data, index):
    if len(data) == 0:
        return 0

    timeStr = getCurTime(20)

    # exportSkinDataToCHeadFile(path, data, timeStr)

    exportSkinDataToCSourceFile(path, data, index, timeStr)

    return 1

def exportSkinResistorData(parent, data, index):
    formatList = 'csv Files (*.csv);;c Files (*.c);;xlsx Files (*.xlsx);;text Files (*.txt);;mat Files (*.mat)'
    filename, ok = QFileDialog.getSaveFileName(parent, '文件保存', './', formatList)

    if ok == '':
        return

    fmt = os.path.splitext(filename)[1]
    fmt = fmt.lower()

    # 导出txt csv文件
    if fmt == '.txt' or fmt == '.csv':
        if exportSkinDataToCsvFile(filename, data) == 0:
            QMessageBox.critical(parent, "错误", filename + "文件保存失败!")
        else:
            QMessageBox.information(parent, "成功", filename + "文件保存成功!")
    # 导出excel文件
    elif fmt == '.xlsx':
        if exportSkinDataToExcelFile(filename, data) == 0:
            QMessageBox.critical(parent, "status", filename + "文件保存失败!")
        else:
            QMessageBox.information(parent, "成功", filename + "文件保存成功!")
    # 导出MAT文件
    elif fmt == '.mat':
        if exportSkinDataToMatFile(filename, data) == 0:
            QMessageBox.critical(parent, "status", filename + "文件保存失败!")
        else:
            QMessageBox.information(parent, "成功", filename + "文件保存成功!")
    # 导出C文件数据
    elif fmt == '.c':
        if exportSkinDataToLanguageCFile(filename, data, index) == 0:
            QMessageBox.critical(parent, "status", filename + "文件保存失败!")
        else:
            QMessageBox.information(parent, "成功", filename + "文件保存成功!")
    else:
        QMessageBox.critical(parent, "status", filename + "文件保存失败，不支持的文件格式!")

def str2AutoNum(s):
    if type(eval(s)) == float:
        return float(s)

    return int(s)

def getCurTime(format=0):
    time = QDateTime.currentDateTime()#获取当前时间

    if format == 1:
        fmt = 'hh:mm:ss.zzz'
    elif format == 2:
        fmt = 'yyyy:MM:dd'
    elif format == 3:
        fmt = 'yyyy:MM:dd-hh:mm:ss'
    elif format == 4:
        fmt = 'yyyy-MM-dd hh:mm:ss'
    elif format == 10:
        fmt = 'yyyy:MM:dd-hh:mm:ss.zzz'
    elif format == 20:
        fmt = 'yyyyMMddhhmmss'
    elif format == 21:
        fmt = 'MMddhhmmss'
    else:
        fmt = 'hh:mm:ss'

    timedisplay = time.toString(fmt)#格式化一下时间

    return timedisplay

def ms2formatStr(time, fmt = 1):
    ms = int(time%1000)
    sec = int(time / 1000)
    minute = int(sec / 60)
    hour = int(minute / 60)

    if fmt == 1:
        out = '{:0>2d}:{:0>2d}:{:0>3d}'.format(minute, sec, ms)
    else:
        out = '{:0>2d}:{:0>2d}:{:0>2d}'.format(hour, minute, sec)

    return out
